package kv

import (
	"errors"
	"os"
	"sync"
)

// const fileDir = "/home/zurry/test/data/"
const fileDir = "E:\\Code\\test\\data\\"

type DBFile struct {
	file   *os.File
	mutex  *sync.Mutex
	offset int64
}

func NewDBFile(filename string) (*DBFile, error) {

	if _, err := os.Stat(fileDir + filename); err != nil {
		if errs := os.MkdirAll(fileDir, 0755); errs != nil {
			return nil, errors.New("创建目录失败.")
		}
	}
	file, err := os.OpenFile(fileDir+filename, os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		return nil, errors.New("打开文件失败.")
	}
	return &DBFile{
		file:  file,
		mutex: &sync.Mutex{},
	}, nil
}

func (db *DBFile) Read(offset int64) (*Entry, error) {
	db.mutex.Lock()
	defer db.mutex.Unlock()

	_, err := db.file.ReadAt(buf, offset)
	if err != nil {
		return nil, errors.New("读取失败.")
	}
	return buf, nil
}

func (db *DBFile) Write(entry *Entry) error {
	db.mutex.Lock()
	defer db.mutex.Unlock()
	buf, err := entry.Encode()
	if err != nil {
		return errors.New("编码失败.")
	}
	_, err = db.file.WriteAt(buf, db.offset)
	if err != nil {
		return errors.New("写入失败.")
	}
	db.offset += entry.GetSize()
	return nil
}
